/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import bean.LiveServersBean;
import bean.LoginActionFormBean;
import dao.ActivityHistoryCrud;
import dao.LiveServersDao;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.LiveServersModel;
import model.LogFile;
import model.OSDetector;
import model.ScheduledTaskLinux;
import model.ScheduledTaskWindows;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import pojo.Activities;
import pojo.ActivityHistory;
import pojo.LiveServers;
import pojo.MyLST;

/**
 *
 * @author A7med Kotb
 */
// class that deals with all live server issues
public class LiveServersAction extends org.apache.struts.actions.DispatchAction {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    //method to add new live server to our servers
    public ActionForward Add(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        System.out.println("Hello Add New Live Server");
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        LiveServersBean lsb = (LiveServersBean) form;
        LiveServers ls = new LiveServers();
        ls.setIp(lsb.getIp());
        ls.setType(lsb.getType());
        ls.setUserName(lsb.getUserName());
        ls.setPassword(lsb.getPassword());
        int port = Integer.parseInt(lsb.getPort());
        ls.setPort(port);
        ls.setDescription(lsb.getDescription());

        MyLST lst = new MyLST();
        lst.setSchedule(lsb.getSchedule());
        lst.setModifier(lsb.getModifier());
        lst.setStartDate(lsb.getStartDated());
        lst.setStartTime(lsb.getStartTime());
        if (lsb.getSchedule().equalsIgnoreCase("hourly") || lsb.getSchedule().equalsIgnoreCase("daily")) {
            lsb.setDay(null);
        }
        if (lsb.getDay() != null) {
            String[] selectedDays = lsb.getDay();
            String days = "";
            for (int i = 0; i < selectedDays.length; i++) {
                days += selectedDays[i] + ",";
            }
            int strlen = days.length();
            int lastindex = strlen - 1;
            String taskdays = days.substring(0, lastindex);
            lst.setDay(taskdays);
        } else {
            lst.setDay(null);
        }
        if (lsb.getMonth() != null) {
            String[] selectedMonths = lsb.getMonth();
            String months = "";
            for (int i = 0; i < selectedMonths.length; i++) {
                months += selectedMonths[i] + ",";
            }
            int monthslen = months.length();
            int lastmonthsindex = monthslen - 1;
            String taskmonths = months.substring(0, lastmonthsindex);
            lst.setMonth(taskmonths);
        } else {
            lst.setMonth(null);
        }
        lst.setIsEnable(true);
        lst.setIsRunning(false);
        LiveServersModel lsm = new LiveServersModel(getDataSource(request, "MyDS").getConnection());
        lsm.add(ls, lst);
        if (OSDetector.isWindows()) {
            new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).createLiveServerTask(lst, ls);
        }
        if (OSDetector.isUnix()) {
            new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).createLiveServerTask(lst, ls);
        }
        boolean logresult = activityHistory("Define New Live Server", request, lsb.getIp());
        if (logresult == true) {
            LogFile.log(" System ", " Logged the operation of adding the Following live Server " + lsb.getIp() + " manually at " + new Date());
        } else {
            LogFile.log(" System ", " failed to log the operation of adding the following live server " + lsb.getIp());
        }
        return mapping.findForward(SUCCESS);
    }

    //method to delete the live server    
    public ActionForward Delete(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        ActionForward forward = new ActionForward();
        LiveServersBean lsb = (LiveServersBean) form;
        int lstId = Integer.parseInt(request.getParameter("lsId"));
        LiveServersDao lsd = new LiveServersDao(getDataSource(request, "MyDS").getConnection());
        LiveServers ls = lsd.getById(lstId);
        boolean logresult = activityHistory("Delete Live Server", request, ls.getIp());
        boolean deletetaskresult = false;
        boolean deletedbresult = false;
        if (OSDetector.isWindows()) {
            deletetaskresult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).deleteLiveServerTask(lstId);
            deletedbresult = new LiveServersModel(getDataSource(request, "MyDS").getConnection()).deleteLiveServer(lsb.getIp());
        }
        if (OSDetector.isUnix()) {
            deletetaskresult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).deleteLiveServerTask(lstId);
            deletedbresult = new LiveServersModel(getDataSource(request, "MyDS").getConnection()).deleteLiveServer(lsb.getIp());
        }
        if (deletedbresult == true && deletetaskresult) {
            LogFile.log(loginbean.getUserName(), "deleted  the following live server " + lsb.getIp());
        } else {
            LogFile.log(" System ", "failed to delete the live server with the IP  " + lsb.getIp());
        }
        if (logresult == true) {
            LogFile.log(" System ", " Logged the operation of deleting the Following live Server " + lsb.getIp() + " manually at " + new Date());
        } else {
            LogFile.log(" System ", " failed to log the operation deleting the following live server " + lsb.getIp());
        }
        return forward = Display(mapping, form, request, response);
    }

    public ActionForward Edit(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        LiveServersBean lsb = (LiveServersBean) form;
        System.out.println("Ipmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm" + request.getParameter("ip"));
        LiveServers ls = new LiveServersModel(getDataSource(request, "MyDS").getConnection()).getByName(lsb.getIp());
        MyLST lst = new LiveServersModel(getDataSource(request, "MyDS").getConnection()).getById(ls.getLsId());
        request.setAttribute("data", ls);
        request.setAttribute("LST", lst);
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        String reportDate = df.format(lst.getStartDate());
        System.out.println("reportDate is Equal to " + reportDate);
        request.setAttribute("startdate", reportDate);
        return mapping.findForward("show");
    }

    //List All Live Servers Available
    public ActionForward Display(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Vector<LiveServers> servers = new LiveServersModel(getDataSource(request, "MyDS").getConnection()).getAllServers();
        //MyLST lst=new LiveServersModel(getDataSource(request, "MyDS").getConnection()).getById(ls.getLsId());
        request.setAttribute("servers", servers);
        System.out.println("Vector Size " + servers.size());
        return mapping.findForward("display");
    }

    //method to update live server data 
    public ActionForward Update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        LiveServersBean lsb = (LiveServersBean) form;

        LiveServers ls = new LiveServers();
        ls.setIp(lsb.getIp());
        ls.setType(lsb.getType());
        ls.setUserName(lsb.getUserName());
        ls.setPassword(lsb.getPassword());
        int port = Integer.parseInt(lsb.getPort());
        ls.setPort(port);
        ls.setDescription(lsb.getDescription());

        MyLST lst = new MyLST();
        lst.setSchedule(lsb.getSchedule());
        lst.setModifier(lsb.getModifier());
        lst.setStartDate(lsb.getStartDated());
        lst.setStartTime(lsb.getStartTime());
        if (lsb.getSchedule().equalsIgnoreCase("hourly") || lsb.getSchedule().equalsIgnoreCase("daily")) {
            lsb.setDay(null);
        }
        if (lsb.getDay() != null) {
            String[] selectedDays = lsb.getDay();
            String days = "";
            for (int i = 0; i < selectedDays.length; i++) {
                days += selectedDays[i] + ",";
            }
            int strlen = days.length();
            int lastindex = strlen - 1;
            String taskdays = days.substring(0, lastindex);
            lst.setDay(taskdays);
        } else {
            lst.setDay(null);
        }
        if (lsb.getMonth() != null) {
            String[] selectedMonths = lsb.getMonth();
            String months = "";
            for (int i = 0; i < selectedMonths.length; i++) {
                months += selectedMonths[i] + ",";
            }
            int monthslen = months.length();
            int lastmonthsindex = monthslen - 1;
            String taskmonths = months.substring(0, lastmonthsindex);
            lst.setMonth(taskmonths);
        } else {
            lst.setMonth(null);
        }
        lst.setIsEnable(true);
        lst.setIsRunning(false);

        LiveServersModel lsm = new LiveServersModel(getDataSource(request, "MyDS").getConnection());
        LiveServers lsold = lsm.getByName(lsb.getIp());
        lst.setLstId(lsold.getLsId());

        boolean updatedbresult = lsm.update(ls, lst);
        boolean deleteresult = false;
        boolean createresult = false;
        if (OSDetector.isWindows()) {
            deleteresult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).deleteLiveServerTask(lst.getLstId());
            createresult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).createLiveServerTask(lst, ls);
        }
        if (OSDetector.isUnix()) {
            deleteresult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).deleteLiveServerTask(lst.getLstId());
            createresult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).createLiveServerTask(lst, ls);
        }
        boolean logresult = activityHistory("Update Live Server", request, lsb.getIp());
        if (deleteresult == true && createresult == true && updatedbresult) {
            LogFile.log(loginbean.getUserName(), "updated data of the live server " + lsb.getIp());
        } else {
            LogFile.log(" System ", "failed to update data of the live server   " + lsb.getIp());
        }
        if (logresult == true) {
            LogFile.log(" System ", " Logged the operation of updating data of the Following live Server " + lsb.getIp() + " manually at " + new Date());
        } else {
            LogFile.log(" System ", " failed to log the operation updating the following live server " + lsb.getIp());
        }
        ActionForward forward = new ActionForward();
        return null;
    }

    //Method to Start Live Server Task Now
    public ActionForward Start(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward forward = new ActionForward();
        LiveServersBean lsb = (LiveServersBean) form;
        String serverIP = request.getParameter("ip");
        System.out.println("Server IP is : " + serverIP);
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        boolean startresult = false;
        if (OSDetector.isWindows()) {
            startresult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).startLiveServerTask(serverIP);
        }
        if (OSDetector.isUnix()) {
            startresult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).startLiveServerTask(serverIP);
        }
        return forward = Display(mapping, form, request, response);
    }

    //method to enable task of live server
    public ActionForward Enable(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward forward = new ActionForward();
        LiveServersBean lsb = (LiveServersBean) form;
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        boolean enableResult = false;
        if (OSDetector.isWindows()) {
            enableResult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).enableLiveServerTask(lsb.getIp());
        }
        if (OSDetector.isUnix()) {
            enableResult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).enableLiveServerTask(lsb.getIp());
        }
        return null;
    }

    //method to disable Schedule Task of live Server
    public ActionForward Disable(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward forward = new ActionForward();
        LiveServersBean lsb = (LiveServersBean) form;
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        boolean disableResult = false;
        if (OSDetector.isWindows()) {
            disableResult = new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).disableLiveServerTask(lsb.getIp());
        }
        if (OSDetector.isUnix()) {
            disableResult = new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).disableLiveServerTask(lsb.getIp());
        }
        return null;
    }
//Add Activity to Activity History

    public boolean activityHistory(String activityName, HttpServletRequest request, String LiveServerIP) {
        boolean check = false;
        try {
            LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
            ActivityHistory log = new ActivityHistory();
            log.setAdminName(loginbean.getUserName());
            log.setLiveServer(LiveServerIP);
            log.setStatus("Success");
            log.setProviderName(null);
            ActivityHistoryCrud ahc = new ActivityHistoryCrud(getDataSource(request, "MyDS").getConnection());
            Activities act = ahc.getByName(activityName);
            log.setActivities(act);
            log.setActivityName(act.getName());
            check = ahc.add(log);
        } catch (SQLException ex) {
            check = false;
            LogFile.log(" System ", " encountered the following exception while trying to log that activity " + ex.getMessage());
            Logger.getLogger(STOperations.class.getName()).log(Level.SEVERE, null, ex);
        }
        return check;
    }
}
